package com.hk.commons.util;


import lombok.AccessLevel;
import lombok.NoArgsConstructor;

import java.util.Objects;

/**
 * @author Kevin
 * @date 2023-05-03 08:56
 */
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public abstract class SnowflakeUtils {

    private static SnowflakeIdGenerator idGenerator;

    /**
     * 要保证单例，不然多个实例，会生成重复的ID
     */
    public static SnowflakeIdGenerator getIdGenerator() {
        if (Objects.nonNull(SnowflakeUtils.idGenerator)) {
            return idGenerator;
        }
        synchronized (SnowflakeUtils.class) {
            if (Objects.isNull(idGenerator)) {
                idGenerator = SpringContextHolder.getBeanIfExist(SnowflakeProperties.class)
                        .map(item -> new SnowflakeIdGenerator(item.getWorkerId(), item.getDataCenterId()))
                        .orElse(new SnowflakeIdGenerator());
            }
        }
        return idGenerator;
    }
}
